/**
 * @author Tobias Boehm
 *
 * 22.06.2011
 */
package org.anddev.andengine.extension.tbsengine.gameobject.animation;

import java.util.Arrays;

import org.anddev.andengine.entity.sprite.AnimatedSprite;

/**
 * This class represents an object animation. 
 * 
 * @author Tobias Boehm
 *
 */
public class ObjectAnimation {

	private static final long DEFAULT_FRAME_DURATION = 200;
	private static final int LOOP_CONTINUOUS = -1;
	
	private final AnimatedSprite mAnimatedSprite;
	private final long[] mFrameDurations;
	private final int[] mAnimationTileIndexes;
	private final int mStandTileIndex;
	
	public ObjectAnimation(final AnimatedSprite pAnimatedSpirte, final int pStandTileIndex){
		
		this(pAnimatedSpirte, DEFAULT_FRAME_DURATION, pStandTileIndex);
	}
	
	public ObjectAnimation(final AnimatedSprite pAnimatedSpirte, final long pFrameDuration, final int pStandTileIndex){
		
		this(pAnimatedSpirte, pFrameDuration, null, pStandTileIndex);
	}
	
	public ObjectAnimation(final AnimatedSprite pAnimatedSpirte, final long pFrameDuration, final int[] pAnimationTileIndexes, final int pStandTileIndex){
			
		this(pAnimatedSpirte, new long[]{pFrameDuration}, pAnimationTileIndexes, pStandTileIndex);
	}
	
	public ObjectAnimation(final AnimatedSprite pAnimatedSpirte, final long[] pFrameDurations, final int[] pAnimationTileIndexes, final int pStandTileIndex){
				
		if(pFrameDurations == null){
			
			throw new IllegalArgumentException("You have to provide an pFrameDurations array with at least one element.");
		}

		this.mStandTileIndex = pStandTileIndex;
		
		this.mAnimatedSprite = pAnimatedSpirte;
				
		// Calculate indexes if not predefined.
		if(pAnimationTileIndexes == null){
			
			this.mAnimationTileIndexes = new int[pAnimatedSpirte.getTextureRegion().getTileCount()];
			
			for(int pos = 0; pos < this.mAnimationTileIndexes.length; pos++){
				
				this.mAnimationTileIndexes[pos] = pos;
			}
						
		}else{
			
			this.mAnimationTileIndexes = pAnimationTileIndexes;
		}
		
		// Calculate frame durations if not predefined.
		if(pFrameDurations.length < this.mAnimationTileIndexes.length){
			
			this.mFrameDurations = new long[this.mAnimationTileIndexes.length];
			
			Arrays.fill(this.mFrameDurations, pFrameDurations[0]);
		
		}else{
		
			this.mFrameDurations = pFrameDurations;
		}
	}
	
	public void play(){
	
		this.mAnimatedSprite.animate(this.mFrameDurations, this.mAnimationTileIndexes, LOOP_CONTINUOUS);
	}
	
	public void stop(){
		
		this.mAnimatedSprite.stopAnimation(this.mStandTileIndex);
	}
}
